package com.yunhe.tianhe.rentcars.filter;

import com.yunhe.tianhe.rentcars.entity.permission.Account;
import com.yunhe.tianhe.rentcars.entity.permission.Resource;
import com.yunhe.tianhe.rentcars.service.permission.ResourceService;
import com.yunhe.tianhe.rentcars.service.permission.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class PermiFilter implements HandlerInterceptor {
    @Autowired
    private ResourceService resourceService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object o) throws Exception {
        Account account = (Account) req.getSession().getAttribute("account");
        Long roleId = 0l;
        String requestURI = req.getRequestURI();
        if (requestURI.equals("/login") || requestURI.equals("/login/verify") || requestURI.startsWith("/static/") || requestURI.startsWith("/kaptcha.jpg")) {   //登录页面
            return true;  //放过访问
        } else if (null == account) {  //未登录
            resp.sendRedirect(req.getContextPath() + "/login");
            return false;
        } else if (null != account) {
            roleId = account.getRoleId();
            String aa = req.getRequestURI();
            List<String> list = new ArrayList<>();
            List<Resource> permissions = resourceService.findByRole(roleId);
            for (Resource i : permissions) {
                String s = i.getRelateUrl();
                list.add(s);
            }
            if (list.contains(aa)) {
                return true;
            }else{
                return false;
            }
        } else {
            resp.sendError(401, "权限不足");
            return false;
        }

    }






    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
